import os
from datetime import datetime
import cv2  # 需要安装 opencv-python
import random  # 添加random模块

class VideoProcessor:
    """处理视频文件的类"""
    
    def __init__(self, video_path):
        self.video_path = video_path
        
    def process(self):
        """处理视频，提取并显示信息"""
        try:
            # 首先重命名文件
            self.rename_file()
            
            # 使用 OpenCV 读取视频信息
            cap = cv2.VideoCapture(self.video_path)
            if not cap.isOpened():
                raise Exception("无法打开视频文件")
                
            # 获取视频信息
            fps = cap.get(cv2.CAP_PROP_FPS)
            frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            duration = frame_count / fps if fps > 0 else 0
            
            print("===========================================")    
            print(f'\n处理视频: {self.video_path}')
            print(f'时长: {duration:.2f}秒')
            print(f'分辨率: {width}x{height}')
            print(f'帧率: {fps:.2f}fps')
            
            # 释放资源
            cap.release()
                
        except Exception as e:
            print(f'处理视频时出错 {self.video_path}: {str(e)}')
    
    def rename_file(self):
        """根据修改日期重命名视频文件"""
        try:
            # 检查文件是否存在且可访问
            if not os.path.isfile(self.video_path):
                raise Exception("文件不存在或无法访问")
                
            # 获取文件所在目录和扩展名
            directory = os.path.dirname(self.video_path)
            ext = os.path.splitext(self.video_path)[1].lower()
            
            # 使用文件修改时间
            try:
                mtime = os.path.getmtime(self.video_path)
                date_str = datetime.fromtimestamp(mtime).strftime('%Y%m%d_%H%M%S')
            except Exception as e:
                print(f"获取文件时间失败，使用当前时间: {str(e)}")
                date_str = datetime.now().strftime('%Y%m%d_%H%M%S')
            
            # 生成新文件名
            counter = 0
            while True:
                suffix = f'_{counter}' if counter > 0 else ''
                new_name = f'VID_{date_str}{suffix}{ext}'
                new_path = os.path.join(directory, new_name)
                
                if not os.path.exists(new_path) or new_path == self.video_path:
                    break
                counter += 1
            
            # 如果文件名不同，则重命名
            if new_path != self.video_path:
                try:
                    os.rename(self.video_path, new_path)
                    print(f'重命名文件: {os.path.basename(self.video_path)} -> {new_name}')
                    self.video_path = new_path
                except PermissionError:
                    print(f"无权限重命名文件: {self.video_path}")
                except OSError as e:
                    print(f"重命名文件时发生系统错误: {str(e)}")
                
        except Exception as e:
            print(f'重命名文件时出错 {self.video_path}: {str(e)}') 